import 'package:flutter/cupertino.dart';
import 'package:flutter_demo/http/user.dart';
import 'package:flutter_demo/models/request/user_login_req.dart';
import 'package:flutter_demo/services/config.dart';
import 'package:flutter_demo/services/user.dart';
import 'package:get/get.dart';

import '../../models/user_token_model.dart';
import '../../routers/names.dart';
import '../../utils/encrypt.dart';
import '../../utils/loading.dart';


class LoginController extends GetxController {
  /// 用户名
  TextEditingController userNameController = TextEditingController(text: "duxin");

  /// 密码
  TextEditingController passwordController = TextEditingController(text: "12345678");

  /// 表单 key
  GlobalKey formKey = GlobalKey<FormState>();

  /// Sign In 登入
  Future<void> onSignIn() async {
    if ((formKey.currentState as FormState).validate()) {
      try {
        var password = EncryptUtil().aesEncode(passwordController.text);
        Loading.show();
        UserLoginReq userLoginReq = UserLoginReq(username: userNameController.text,password: password);
        UserTokenModel userTokenModel = await UserApi.login(userLoginReq);
        String? token = userTokenModel.token;
        if(token!=null && token.isNotEmpty){
          UserService.to.setToken(token);
          ///登录成功-》获取用户资料
          await UserService.to.getProfile();
          ///页面跳转
          Get.offNamed(RouteNames.systemHome);
        }
      } finally {
        Loading.dismiss();
      }
    }
  }

  /// Sign Up 注册
  void onSignUp() {
    Get.toNamed(RouteNames.systemRegister);
  }



  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    ConfigService.to.setAlreadyOpen();//标记是不是第一次打开
  }

  @override
  void onClose() {
    super.onClose();
    userNameController.dispose();
    passwordController.dispose();
  }

}
